package com.junglone;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.pool.HikariPool;

public class DataSourceConfig {

	Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
	
	private static final DataSourceConfig DATA_SOURCE_CONFIG = new DataSourceConfig();

	private static HikariPool HIKARI_POOL = null;
	
	static {
		
		HikariConfig hikariConfig = new HikariConfig();
		hikariConfig.setDriverClassName("com.mysql.jdbc.Driver");
		hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/test");
		hikariConfig.setUsername("root");
		hikariConfig.setPassword("root");
		hikariConfig.setMaximumPoolSize(5);
		hikariConfig.setMinimumIdle(3);
		hikariConfig.setConnectionTimeout(60000L);
		hikariConfig.addDataSourceProperty("cachePrepStmts", "true");
		hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250");
		hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
		hikariConfig.addDataSourceProperty("useServerPrepStmts", "true");
		hikariConfig.addDataSourceProperty("useLocalSessionState", "true");
		hikariConfig.addDataSourceProperty("rewriteBatchedStatements", "true");
		hikariConfig.addDataSourceProperty("cacheResultSetMetadata", "true");
		hikariConfig.addDataSourceProperty("cacheServerConfiguration", "true");
		hikariConfig.addDataSourceProperty("elideSetAutoCommits", "true");
		hikariConfig.addDataSourceProperty("maintainTimeStats", "true");
		HIKARI_POOL = new HikariPool(hikariConfig);
		
	}
	
	
	private DataSourceConfig() {}
	
	public static synchronized DataSourceConfig getInstance() {
		return DATA_SOURCE_CONFIG;
	}
	
	public Connection getConnection() throws SQLException {
		logger.info("-- getActiveConnections == {}, getTotalConnections == {}, "
				+ "getIdleConnections == {}, getThreadsAwaitingConnection == {}", 
				HIKARI_POOL.getActiveConnections(), 
				HIKARI_POOL.getTotalConnections(), 
				HIKARI_POOL.getIdleConnections(), 
				HIKARI_POOL.getThreadsAwaitingConnection());
		return HIKARI_POOL.getConnection();
	}
	
	
}
